<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <link th:href="@{favicon.ico}"  rel="shortcut icon"/>
    <title>主页</title>
<!--    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">-->
    <link rel="stylesheet" href="/css/vue/index.css">
</head>
<body>

<div id="app">
    <el-container>
        <el-header style="min-height: 70px">
            欢迎微博主页
            <a href="/users/login#/blogList">去微博列表</a>
            <h3 th:if="${session.users != null}">
                欢迎<span th:text="${session.users.username}"></span>登录微博系统。
            </h3>
        </el-header>
        <el-container>
<!--            aside开始-->
            <el-aside width="200px">

                <el-row class="tac">
                    <el-col :span="24">
                        <h5>默认颜色</h5>
                        <el-menu
                                :default-active="this.$route.path"
                                router
                                class="el-menu-vertical-demo"
                                @open="handleOpen"
                                @close="handleClose">
                            <el-submenu index="1">
                                <template slot="title">
                                    <i class="el-icon-location"></i>
                                    <span>微博管理</span>
                                </template>
                                <el-menu-item-group>
                                    <el-menu-item index="/blogList" >微博列表</el-menu-item>
                                    <el-menu-item index="/addBlog">添加微博</el-menu-item>
                                </el-menu-item-group>
                            </el-submenu>
                            <el-submenu index="2">
                                <template slot="title">
                                    <i class="el-icon-location"></i>
                                    <span>账户管理</span>
                                </template>
                                <el-menu-item-group>

                                    <el-menu-item index="/userList" >账号列表</el-menu-item>
                                    <el-menu-item index="/addUser">添加用户</el-menu-item>
                                </el-menu-item-group>
                            </el-submenu>
                        </el-menu>
                    </el-col>
                </el-row>

            </el-aside>
<!--            aside结束-->
            <el-container>
<!--                main 开始-->
                <el-main>
                    <router-view></router-view>
                </el-main>
<!--                main结束-->
                <el-footer>&copy;工作室Footer</el-footer>
            </el-container>
        </el-container>
    </el-container>
</div>

<template id="blogList">
    <div>
        <el-table
                :data="tableData"
                style="width: 100%">
            <el-table-column
                    prop="id"
                    label="id"
                    width="180">
            </el-table-column>
            <el-table-column
                    label="用户头像"
                    width="120">
                <template scope="scope">
                    <img :src="scope.row.picpath" width="50" height="50" class="head_pic"/>
                </template>
            </el-table-column>
            <el-table-column
                    prop="publishtime"
                    label="发布日期"
                    width="180"
                    :formatter="dateFormat">
            </el-table-column>
            <el-table-column
                    prop="content"
                    label="内容"
                    width="180">
            </el-table-column>
            <el-table-column
                    fixed="right"
                    label="操作"
                    width="120">
                <template scope="scope">
                    <el-button
                            @click.native.prevent="deleteBlog(scope.row.id, scope.row)"
                            type="text"
                            size="small">
                        移除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="block">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pageInfo.current"
                    :page-sizes="[2, 3, 5, 10,20]"
                    :page-size="pageInfo.size"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pageInfo.total">
            </el-pagination>
        </div>
    </div>
</template>

<!--添加微博-->
<template id="addBlog">
    <el-form ref="form" :model="form" status-icon :rules="rules" label-width="80px">
        <el-form-item label="微博内容" prop="content">
            <el-input type="textarea" v-model="form.content"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submit('form')">提交</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<!--用户列表-->
<template id="userList">
    <div>
        <el-table
                :data="userData"
                style="width: 100%">
            <el-table-column
                    prop="id"
                    label="id"
                    width="180">
            </el-table-column>
            <el-table-column
                    label="用户头像"
                    width="120">
                <template scope="scope">
                    <img :src="scope.row.picpath" width="50" height="50" class="head_pic"/>
                </template>
            </el-table-column>
            <el-table-column
                    prop="nickname"
                    label="昵称"
                    width="180">
            </el-table-column>
            <el-table-column
                    prop="mobile"
                    label="手机"
                    width="180">
            </el-table-column>
            <el-table-column
                    prop="address"
                    label="地址"
                    width="180">
            </el-table-column>
            <el-table-column
                    fixed="right"
                    label="操作"
                    width="120">
                <template scope="scope">
                    <el-button
                            @click.native.prevent="deleteUser(scope.row.id, scope.row)"
                            type="text"
                            size="small">
                        移除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="block">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pageInfo.current"
                    :page-sizes="[2, 3, 5, 10,20]"
                    :page-size="pageInfo.size"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pageInfo.total">
            </el-pagination>
        </div>
    </div>
</template>

<!--添加用户-->
<template id="addUser">
    <div>
        <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" size="mini">
            <el-form-item label="账号" prop="username">
                <el-input type="text" v-model="ruleForm.username" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPass">
                <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="年龄" prop="age">
                <el-input v-model.number="ruleForm.age"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
                <el-select v-model="ruleForm.sex" placeholder="请选择性别">
                    <el-option label="男" value="1"></el-option>
                    <el-option label="女" value="2"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="昵称" prop="nickname">
                <el-input type="text" v-model="ruleForm.nickname" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="mobile">
                <el-input type="text" v-model.number="ruleForm.mobile" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="地址" prop="address">
                <el-input type="text" v-model="ruleForm.address" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="头像" prop="picpath">
                <el-upload
                        class="avatar-uploader"
                        action="/users/addPic"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
                <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>


</body>
<!-- import Vue before Element -->
<!-- import JavaScript -->
<script src="/js/vue/vue.js"></script>
<script src="/js/vue/index.js"></script>
<script src="/js/vue/axios.min.js"></script>
<script src="/js/vue/vue-router.js"></script>

<script>

    /**
     * 微博列表
     */
    var BlogList = {
        template:"#blogList",
        data: function() {
            return {
                pageInfo:{},
                tableData:[]
            }
        },
        created(){
            // 分页查询
            this.getBlogPageList(1,5);
        },
        methods: {
            handleSizeChange(size) {
                console.log(`每页 ${size} 条`);
                this.getBlogPageList(this.pageInfo.current,size);
            },
            handleCurrentChange(current) {
                console.log(`当前页: ${current}`);
                this.getBlogPageList(current,this.pageInfo.size);
            },
            getBlogPageList(current,size) {
                axios.get('/blog/getBlogPageList', {
                    params: {
                        current: current,
                        size: size
                    }
                }).then(response => (
                    this.pageInfo = response.data,
                    this.tableData = response.data.records
                )).catch(function (error) {
                    console.log(error);
                })
            },
            //时间格式化
            dateFormat: function(row) {
                //时间格式化
                var t = new Date(row.publishtime)// row 表示一行数据, createTime 表示要格式化的字段名称
                if(!t){
                    return ''
                }
                let year = t.getFullYear()
                let month = this.dateIfAddZero(t.getMonth()+1)
                let day = this.dateIfAddZero(t.getDate())
                // let hours = this.dateIfAddZero(t.getHours())
                // let minutes = this.dateIfAddZero(t.getMinutes())
                // let seconds = this.dateIfAddZero(t.getSeconds())
                return year + '-' + month + '-' + day
                    // + ' ' + hours + ':' + minutes+ ':' + seconds
            },
            dateIfAddZero : function (time) {
                return time < 10 ? '0'+ time : time
            },
            // 删除
            deleteBlog(id, rows) {
                this.$confirm('此操作将永久删除该微博, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.get('/blog/delBlog', {
                        params:{
                            id:id
                        }
                    }).then(response => (
                        this.$message({
                            showClose: true,
                            message: '微博删除成功',
                            type: 'success'
                        }),
                            console.log(this.$router),
                            //this.$router.replace('/blogList')
                            this.getBlogPageList(this.pageInfo.current,this.pageInfo.size)
                    )).catch(function (error) {
                        console.log(error);
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }
        }
    }

    /**
     * 用户列表
     */
    var UserList = {
        template:"#userList",
        data: function() {
            return {
                pageInfo:{},
                userData:[]
            }
        },
        created(){
            // 分页查询
            this.getUserPageList(1,5);
        },
        methods: {
            handleSizeChange(size) {
                console.log(`每页 ${size} 条`);
                this.getUserPageList(this.pageInfo.current,size);
            },
            handleCurrentChange(current) {
                console.log(`当前页: ${current}`);
                this.getUserPageList(current,this.pageInfo.size);
            },
            getUserPageList(current,size) {
                axios.get('/users/getUserPageList', {
                    params: {
                        current: current,
                        size: size
                    }
                }).then(response => (
                    this.pageInfo = response.data,
                        this.userData = response.data.records
                )).catch(function (error) {
                    console.log(error);
                })
            },
            // 删除
            deleteUser(id, rows) {
                this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.get('/users/delUser', {
                        params:{
                            id:id
                        }
                    }).then(response => (
                        this.$message({
                            showClose: true,
                            message: '用户删除成功',
                            type: 'success'
                        }),
                            console.log(this.$router),
                            this.handleCurrentChange(1)
                    )).catch(function (error) {
                        console.log(error);
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }
        }
    }

    /**
     * 添加用户
     */
    var AddUser = {
        template:"#addUser",
        data() {
            var validateUsername = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入用户名'));
                }
                axios.get('/users/checkUserName', {
                    params: {
                        username: value
                    }
                }).then(function (response) {
                    console.log(response);
                    if (response.data) {
                        callback(new Error('用户名以重复'));
                    } else {
                        callback();
                    }
                }).catch(function (error) {
                    console.log(error);
                });
            };
            var checkAge = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('年龄不能为空'));
                }
                setTimeout(() => {
                    if (!Number.isInteger(value)) {
                        callback(new Error('请输入数字值'));
                    }
                    callback();
                }, 1000);
            };
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    if (this.ruleForm.checkPass !== '') {
                        this.$refs.ruleForm.validateField('checkPass');
                    }
                    callback();
                }
            };
            var validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.ruleForm.password) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            var validateSex = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请选择性别'));
                }
                callback();
            };
            var validateNickname = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入昵称'));
                }
                callback();
            };
            var validateMobile = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入电话号码'));
                }
                callback();
            };
            var validateAddress = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入地址'));
                }
                callback();
            };
            var validatePicpath = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请选择用户头像'));
                }
                callback();
            };
            return {
                //上传成功回显展示
                imageUrl: '',
                ruleForm: {
                    username:'',
                    password: '',
                    checkPass: '',
                    age: '',
                    sex: '',
                    nickname: '',
                    mobile: '',
                    address: '',
                    picpath:''
                },
                rules: {
                    username: [
                        { validator: validateUsername, trigger: 'blur' }
                    ],
                    password: [
                        { validator: validatePass, trigger: 'blur' }
                    ],
                    checkPass: [
                        { validator: validatePass2, trigger: 'blur' }
                    ],
                    age: [
                        { validator: checkAge, trigger: 'blur' }
                    ],
                    sex: [
                        { validator: validateSex, trigger: 'change' }
                    ],
                    nickname: [
                        { validator: validateNickname, trigger: 'blur' }
                    ],
                    mobile: [
                        { validator: validateMobile, trigger: 'blur' }
                    ],
                    address: [
                        { validator: validateAddress, trigger: 'blur' }
                    ],
                    picpath: [
                        { validator: validatePicpath, trigger: 'blur' }
                    ]
                }
            };
        },
        methods:{
            //回调成功
            handleAvatarSuccess(res, file) {
                //成功展示图片
                this.imageUrl = URL.createObjectURL(file.raw);
                //上传前的相对路径同步
                this.ruleForm.picpath = res;
            },
            //上传前验证图片格式
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg'||'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG、PNG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        axios.post('/users/addUser', this.ruleForm)
                            .then(response => (
                                this.$message({
                                    showClose: true,
                                    message: '用户保存成功',
                                    type: 'success'
                                }),
                                    console.log(this.$router),
                                    this.$router.replace('/userList')
                            )).catch(function (error) {
                            console.log(error);
                        });
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            turnTo(){
                console.log("测试。。。")
                this.$router.replace('/blogList');
            }
        }

    }

    /**
     * 添加微博
     */
    var AddBlog = {
        template:"#addBlog",
        data() {
            var validateContent = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入微博内容'));
                }
                callback();
            };
            return {
                form: {
                    content:''
                },
                rules: {
                    content: [
                        { validator: validateContent, trigger: 'blur' }
                    ]
                }
            };
        },
        methods:{
            submit(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        axios.post('/blog/addBlog', this.form)
                            .then(response => (
                                this.$message({
                                    showClose: true,
                                    message: '微博发表成功',
                                    type: 'success'
                                }),
                                    console.log(this.$router),
                                    this.$router.replace('/blogList')
                            )).catch(function (error) {
                            console.log(error);
                        });
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            turnTo(){
                console.log("测试。。。")
                this.$router.replace('/blogList');
            }
        }

    }

    const routes = [
        {path:"/blogList",component:BlogList},
        {path:"/addBlog",component:AddBlog},
        {path:"/addUser",component:AddUser},
        {path:"/userList",component:UserList},
        {path:"*",redirect:"/blogList"} //{path:"*",component:Home}
    ];
    const router=new VueRouter({
        routes
    });


    new Vue({
        el: '#app',
        router,
        data: function() {
            return {
            }
        },
        created(){

        },
        methods: {
            // 菜单打开
            handleOpen(key, keyPath) {
                console.log(key, keyPath);
            },
            // 菜单关闭
            handleClose(key, keyPath) {
                console.log(key, keyPath);
            }
        }
    })
</script>
<style>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
    .block{
        margin-top:15px;
    }
    .el-header, .el-footer {
        background-color: #B3C0D1;
        color: #333;
        text-align: center;
    }
    .el-aside {
        background-color: #D3DCE6;
        color: #333;
        text-align: center;
    }
    .el-main {
        background-color: #E9EEF3;
        color: #333;
        text-align: center;
    }

</style>
</html>